import { World } from "./World";

/**
 * System基类
 * 每个system都有一个mask值，用于标识system需要的组件类型
 */
export abstract class System {
    protected _world!: World;
    private _enabled = true;

    set world(val) {
        this._world = val;
    }

    get world() {
        return this._world;
    }

    set enabled(val: boolean) {
        this._enabled = val;
    }

    get enabled() {
        return this._enabled;
    }

    // 系统初始化
    abstract onStart(): void;

    // 系统更新
    abstract onUpdate(deltaTime: number): void;

    // // 获取系统需要的组件mask
    // get requiredComponentMask(): bigint {
    //     return System.getRequiredMask(this.constructor);
    // }

    // static getRequiredMask(type: any): bigint {
    //     return type["RequiredMask"] || 0n;
    // }
}

// export class SystemRegistry {
//     private static _registry = new Map<string, any>();

//     static register(typeName: string, constructor: any) {
//         if (this._registry.has(typeName)) {
//             throw new Error(`System ${typeName} already registered`);
//         }

//         constructor["ClassName"] = typeName;
//         this._registry.set(typeName, constructor);

//         // 日志
//         console.log(`System ${typeName} registered`);
//     }

//     static getByTypeName(typeName: string) {
//         return this._registry.get(typeName);
//     }
// }

// // 通过一个decorator来注册系统
// export function ecs_system(name: string) {
//     return function (target: any) {
//         SystemRegistry.register(name, target);
//     }
// }

// // 通过一个decorator来标记系统需要的组件
// export function ecs_require(...componentTypes: (new () => Component)[]) {
//     return function (target: any) {
//         const mask = componentTypes.reduce((mask, type) => {
//             return mask | Component.getMask(type);
//         }, 0n);
//         target["RequiredMask"] = mask;
//     }
// }

export class SystemManager {
    private _systems: System[] = [];
    private _world: World;
    constructor(world: World) {
        this._world = world;
    }

    start() {
        this._systems.forEach((system) => {
            system.onStart();
        });
    }   

    addSystem<T extends System>(system: new () => T) {
        // system不能重复添加
        if (this._systems.find((s) => s instanceof system)) {
            console.warn(`System ${system.name} already exists`);
            return;
        }
        const instance = new system();
        instance.world = this._world;
        this._systems.push(instance);

        return instance;
    }

    getSystems() {
        return this._systems;
    }

    update(deltaTime: number) {
        this._systems.forEach((system) => {
            if (system.enabled) {
                system.onUpdate(deltaTime);   
            }
        });
    }
}